{% extends "CommonLibraryBundle::base.html.twig" %}

{% form_theme form ':form:form_bootstrap.html.twig' %}

{% block stylesheets %}
    {{ parent() }}
    <link type="text/css" rel="stylesheet" href="{{asset('css/qcm.css')}}" />
{% endblock %}

{% block javascripts %}
    {{parent()}}
{% endblock %}

{% block titre %}
    QCM
{% endblock %}

{% block titresmall %}
    {% if app.request.attributes.get('_route') == 'common_library_qcm_edit' %}
        Ajout d'un QCM
    {% else %}
        Modification d'un QCM
    {% endif %}
{% endblock %}

{% block subbody %}
    <script type="text/javascript">

        $(function () {
            var $container = $('#common_librarybundle_qcmtype_questions');
            // On définit un compteur unique pour nommer les champs qu'on va ajouter dynamiquement
            indexQuestion = $container.find('.qcmQuestion').length;
            // On ajoute un premier champ directement s'il n'en existe pas déjà.
            if (indexQuestion == 0) {
                ajouterBoutonQuestion($container);
                for(var i=0; i<{{ minQuestion }};i++)
                {
                    $container.find('#ajout_question').click();
                }
            } else {
                $container.find('.qcmQuestion').each(function () {
                    indexReponse = 0;
                    $(this).find('.questionReponse').each(function () {
                        if(indexReponse >= 2)
                        {
                            ajouterBoutonSuppressionReponse($(this));
                        }
                        indexReponse++;
                    });
                    if(indexReponse < {{ maxReponse }})
                    {
                        ajouterBoutonReponse($(this).find('.questionReponse').parent());
                    }
                    ajouterBoutonSuppression($(this));
                });
                ajouterBoutonQuestion($container);
            }

            toggleOptionsQCM();
            afficheErreurForm();
        });

        function afficheErreurForm()
        {
            if($("#notif").find('span').length > 0)
            {
                var $span = $("#notif").find('span');
                $span.addClass('alert alert-dismissable');
                $span.prepend('<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>');
            }
        }

        function toggleOptionsQCM()
        {
            $('.qcmOptions').click(function()
            {
                if($(this).parent().next('div').hasClass('hide'))
                {
                    $(this).parent().next('div').removeClass('hide');
                    $(this).find('.glyphicon').removeClass("glyphicon-chevron-down");
                    $(this).find('.glyphicon').addClass("glyphicon-chevron-up");
                }
                else
                {
                    $(this).parent().next('div').addClass('hide');
                    $(this).find('.glyphicon').removeClass("glyphicon-chevron-up");
                    $(this).find('.glyphicon').addClass("glyphicon-chevron-down");
                }
            });
        }

        function toggleOptionsQuestion()
        {
            $('.questionOptions').click(function()
            {
                if($(this).parent().prev('div').hasClass('hide'))
                {

                    $(this).parent().prev('div').removeClass('hide');
                    $(this).find('.glyphicon').removeClass("glyphicon-chevron-down");
                    $(this).find('.glyphicon').addClass("glyphicon-chevron-up");
                }
                else
                {
                    $(this).parent().prev('div').addClass('hide');
                    $(this).find('.glyphicon').removeClass("glyphicon-chevron-up");
                    $(this).find('.glyphicon').addClass("glyphicon-chevron-down");
                }
            });
        }

        function ajouterBoutonQuestion($prototype) {
            // On ajoute un lien pour ajouter une nouvelle catégorie
            var $lienAjout = $('<a href="#" id="ajout_question" class="btn btn-xs btn-primary"><span class="glyphicon glyphicon-plus"></span> Ajouter une question</a>');
            var $lienAjoutExistant = $('<a href="#" id="ajout_question_existante" class="btn btn-xs btn-primary" data-toggle="modal" data-target="#modalAjoutQuestionExistante"><span class="glyphicon glyphicon-plus"></span> Ajouter une question existante</a>')
            $prototype.append($lienAjout);
            $prototype.append($lienAjoutExistant);

            // On ajoute un nouveau champ à chaque clic sur le lien d'ajout.
            $lienAjout.click(function (e) {
                ajouterQuestion($prototype, null);
                e.preventDefault(); // évite qu'un # apparaisse dans l'URL

                var $containerReponse = $('#common_bundle_librarybundle_qcm_questions_'+ (indexQuestion-1) +'_reponses');
                indexReponse = $containerReponse.find(':input').length;

                if (indexReponse == 0) {
                    ajouterBoutonReponse($containerReponse);
                    for(var i=0; i<2;i++)
                    {
                        $containerReponse.find("#ajout_reponse").click();
                    }
                }
                else
                {
//                    $containerReponse.find('.questionReponse').each(function () {
//                        ajouterBoutonSuppressionReponse($(this));
//                    });
                    ajouterBoutonReponse($containerReponse);
                }
                return false;
            });

            $lienAjoutExistant.click(function (e) {
                getLesQcms($prototype);
            });
            toggleOptionsQuestion();
        }

        function getLesQcms($prototype)
        {
            $("#selectTheme").change(function () {
                if(!$('#divChoixQcm').hasClass('hide'))
                {
                    $('#divChoixQcm').addClass('hide');
                }
                if(!$('#divChoixQuestion').hasClass('hide'))
                {
                    $('#divChoixQuestion').addClass('hide');
                    $("#validQuestionExistante").addClass('hide');
                }
                if ($("#selectTheme").val() != '') {
                    var post = {
                        "idTheme" : $("#selectTheme").val()
                    };
                    $.ajax({
                        url: "{{ path('getLesQcms') }}",
                        type: 'POST',
                        data: post,
                        success: function (data) {
                            if (data != 0) {
                                var tabQcm = JSON.parse(data);
                                $("#selectQcm").empty();
                                var $option = '<option value=""></option>';
                                $("#selectQcm").append($option);
                                for(i in tabQcm)
                                {
                                    var $option = '<option value="'+tabQcm[i].id+'">'+tabQcm[i].nom+'</option>';
                                    $("#selectQcm").append($option);
                                }
                                $('#divChoixQcm').removeClass('hide');
                                getLesQuestions($prototype);
                            }
                        }
                    });
                }
            });
        }

        function getLesQuestions($prototype)
        {
            $("#selectQcm").change(function () {
                if(!$('#divChoixQuestion').hasClass('hide'))
                {
                    $('#divChoixQuestion').addClass('hide');
                    $("#validQuestionExistante").addClass('hide');
                }
                if ($("#selectQcm").val() != '') {
                    var post = {
                        "idQcm" : $("#selectQcm").val()
                    };
                    $.ajax({
                        url: "{{ path('getLesQuestions') }}",
                        type: 'POST',
                        data: post,
                        success: function (data) {
                            if (data != 0) {
                                var tabQuestion = JSON.parse(data);
                                $("#selectQuestion").empty();
                                var $option = '<option value=""></option>';
                                $("#selectQuestion").append($option);
                                for(i in tabQuestion)
                                {
                                    var $option = '<option value="'+tabQuestion[i].id+'">'+tabQuestion[i].libelle+'</option>';
                                    $("#selectQuestion").append($option);
                                }
                                $('#divChoixQuestion').removeClass('hide');
                                validerQuestionExistante($prototype, tabQuestion);
                            }
                        }
                    });
                }
            });
        }

        function validerQuestionExistante($prototype, tabQuestion)
        {
            $("#selectQuestion").change(function () {
                if($("#selectQuestion").val() != '')
                {
                    $("#validQuestionExistante").removeClass('hide');
                    $('#validQuestionExistante').click(function()
                    {
                        $("#modalAjoutQuestionExistante").modal("hide");
                        var tabReponse = new Array();
                        for(i in tabQuestion)
                        {
                            if(tabQuestion[i].id == $("#selectQuestion").val())
                            {
                                var question = {
                                    "libelle" : tabQuestion[i].libelle,
                                    "aide" : tabQuestion[i].aide,
                                    "complement" : tabQuestion[i].complementReponse
                                };
                                tabReponse = tabQuestion[i].reponses;
                            }
                        }
                        ajouterQuestion($prototype, question);

                        var $containerReponse = $('#common_bundle_librarybundle_qcm_questions_'+ (indexQuestion-1) +'_reponses');
                        indexReponse = $containerReponse.find(':input').length;
                        ajouterBoutonReponse($containerReponse);
                        for(var i=0; i<tabReponse.length;i++)
                        {
                            $containerReponse.find("#ajout_reponse").click();
                            $containerReponse.find('input[type=text]:eq('+i+')').val(tabReponse[i].libelle);
                            if(tabReponse[i].estCorrecte == 1)
                            {
                                $containerReponse.find('input[type=checkbox]:eq('+i+')').attr('checked', 'checked');
                            }
                        }
                        $("#selectQuestion").empty();
                        $('#divChoixQuestion').addClass('hide');
                        $("#selectQcm").empty();
                        $('#divChoixQcm').addClass('hide');
                        $("#selectTheme option:eq(0)").attr('selected', 'selected');
                        $("#validQuestionExistante").addClass('hide');
                        return false;
                    });
                }
                else if(!$("#validQuestionExistante").hasClass('hide'))
                {
                    $("#validQuestionExistante").addClass('hide');
                }
            });
        }

        function ajouterBoutonReponse($prototype)
        {
            var $lienAjout = $('<a href="#" id="ajout_reponse" class="btn btn-xs btn-primary"><span class="glyphicon glyphicon-plus"></span> Ajouter une réponse</a>');
            $prototype.append($lienAjout);

            // On ajoute un nouveau champ à chaque clic sur le lien d'ajout.
            $lienAjout.click(function (e) {
                ajouterReponse($prototype);
                e.preventDefault(); // évite qu'un # apparaisse dans l'URL
                return false;
            });
        }

        function ajouterReponse($container){
            $($container.find("#ajout_reponse")).remove();

            var $prototype = $($container.attr('data-prototype').replace(/reponses_name/g, indexReponse));
            $prototype.addClass("questionReponse bs-callout bs-callout-violet");
            $prototype.find("input:eq(0)").parent().parent().wrap('<div class="col-md-1 linef"></div>');
            $prototype.find("input:eq(1)").parent().wrap('<div class="col-md-10 linef"></div>');
            $prototype.find(".linef").wrapAll( "<div class='row'></div>");
            // suppression des labels
            $prototype.find("label").remove();
            // On ajoute le prototype modifié à la fin de la balise <div>
            $container.append($prototype);
            var i = 0;
            $container.find('.questionReponse').each(function()
            {
                i++
            });
            if(i >= 3)
            {
                ajouterBoutonSuppressionReponse($prototype);
            }
            if(i <= 3)
            {
                ajouterBoutonReponse($container);
            }
            indexReponse++;
        }

        function ajouterQuestion($container, question){
            $("#ajout_question").remove();
            $("#ajout_question_existante").remove();

            var $prototype = $($container.attr('data-prototype').replace(/questions_name/g, indexQuestion));
            $prototype.addClass("qcmQuestion bs-callout bs-callout-violet");
            $prototype.prepend('<h4>Question</h4>');
            $prototype.find("input:eq(0)").parent().wrap('<div class="col-md-8 linef"></div>');
            $prototype.find("select:eq(0)").parent().parent().wrap('<div class="col-md-4 linef"></div>');
            $prototype.find("textarea:eq(0)").parent().wrap('<div class="col-md-6 lines"></div>');
            $prototype.find("textarea:eq(1)").parent().wrap('<div class="col-md-6 lines"></div>');
            $prototype.find(".linef").wrapAll( "<div class='row'></div>");
            $prototype.find(".lines").wrapAll( "<div class='row hide'></div>");
            $prototype.find("div.row:eq(1)").after('<div><a class="btn btn-default btn-xs questionOptions"><span class="glyphicon glyphicon-chevron-down"></span> Options</a></div><br><h4>Réponses</h4><div class="row"><div class="col-md-1 labelReponse">Correcte</div><div class="col-md-9 labelReponse">Libellé</div></div>');
            // suppression des labels
            $prototype.find("label").remove();
            // On ajoute le prototype modifié à la fin de la balise <div>
            $container.append($prototype);

            $("<label [for='common_librarybundle_qcmtype_questions_" + indexQuestion + "_libelle']>Libellé</label>").insertBefore($prototype.find("input:eq(0)"));
            $("<label [for='common_librarybundle_qcmtype_questions_" + indexQuestion + "_aide']>Aide</label>").insertBefore($prototype.find("textarea:eq(0)"));
            $("<label [for='common_librarybundle_qcmtype_questions_" + indexQuestion + "_complementReponse']>Complément de réponse</label>").insertBefore($prototype.find("textarea:eq(1)"));
            $("<label [for='common_librarybundle_qcmtype_questions_" + indexQuestion + "_typeQuestion']>Type de question</label>").insertBefore($prototype.find("select:eq(0)").parent());

//            $("<h4>Réponses :</h4>").insertBefore($prototype.find("div.form-group:last"));
            if(question != null)
            {
                $prototype.find("input:eq(0)").val(question.libelle);
                $prototype.find("input:eq(1)").val(question.aide);
                $prototype.find("input:eq(2)").val(question.complementReponse);
            }
            ajouterBoutonSuppression($prototype);
            if(indexQuestion < {{ maxQuestion }}-1)
            {
                ajouterBoutonQuestion($container);
            }
            indexQuestion++;
        }

        // La fonction qui ajoute un lien de suppression d'une catégorie
        function ajouterBoutonSuppression($prototype) {
            // Création du lien
            $lienSuppression = $('<a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-minus"></span> Supprimer la question</a><br/>');

            // Ajout du lien
            $prototype.append($lienSuppression);

            // Ajout du listener sur le clic du lien
            $lienSuppression.click(function (e) {
                indexQuestion--;
                indexReponse = 0;
                $(this).parent().remove();
                e.preventDefault(); // évite qu'un # apparaisse dans l'URL
                return false;
            });
        }

        // La fonction qui ajoute un lien de suppression d'une catégorie
        function ajouterBoutonSuppressionReponse($prototype) {
            // Création du lien
            $lienSuppression = $('<div class="col-md-1"><div class="form-group"><a href="#" class="btn btn-danger btn-xs delReponse"><span class="glyphicon glyphicon-minus"></span></a></div></div>');

            // Ajout du lien
            $lienSuppression.insertAfter($prototype.find('input:eq(1)').parent().parent());

            // Ajout du listener sur le clic du lien
            $lienSuppression.click(function (e) {
                var $parent = $(this).parent().parent().parent().parent();
                indexReponse--;
                $(this).parent().parent().parent().remove();
                var j = 0;
                $parent.find('.questionReponse').each(function()
                {
                    j++
                });
                if(j == 3)
                {
                    ajouterBoutonReponse($parent);
                }
                e.preventDefault(); // évite qu'un # apparaisse dans l'URL
                return false;
            });
        }
    </script>

    <div class="modal fade" id="modalAjoutQuestionExistante" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">Ajouter une question existante</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group ">
                        <label>Thème</label>
                        <div class="controls">
                            <select id="selectTheme" class="input-sm form-control">
                                <option value=""></option>
                                {% for theme in themes %}
                                    <option value="{{ theme.id }}">{{ theme.nom }}</option>
                                {% endfor %}
                            </select>
                        </div>
                    </div>
                    <div class="form-group ">
                        <div id="divChoixQcm" class="hide">
                            <label>QCM</label>
                            <div class="controls">
                                <select id="selectQcm" class="input-sm form-control"></select>
                            </div>
                        </div>
                    </div>
                    <div class="form-group ">
                        <div id="divChoixQuestion" class="hide">
                            <label>Question</label>
                            <div class="controls">
                                <select id="selectQuestion" class="input-sm form-control"></select>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>
                    <button type="button" id="validQuestionExistante" class="btn btn-success hide">Valider</button>
                </div>
            </div>
        </div>
    </div>
    <div id="notif">{{ form_errors(form) }}</div>
    <form action="" method="post" class="" {{ form_enctype(form) }}>
        <div id="formModificationQCM" class="well {% if app.request.attributes.get('_route') == 'common_library_qcm_editquestionsreponses' %}hide{% endif %}">
            <div class="row">
                <div class="col-md-8">{{ form_row(form.nom, {'label': 'Nom'}) }}</div>
                <div class="col-md-4">{{ form_row(form.theme, {'label': 'Thème'}) }}</div>
            </div>
            <div>
                <a class="btn btn-default qcmOptions"><span class="glyphicon glyphicon-chevron-up"></span> Options</a>
            </div>
            <div class="row">
                <div class="col-md-8">{{ form_row(form.description, {'label': 'Description'}) }}</div>
                <div class="col-md-4">
                    {{ form_row(form.niveau, {'label': 'Niveau'}) }}
                    {{ form_row(form.difficulte, {'label': 'Difficulté'}) }}
                </div>
            </div>
        </div>
        <h4>Questions</h4>
        <div id="common_librarybundle_qcmtype_questions" data-prototype="{{ form_widget(form.questions.vars.prototype)|e }}">
            {% for question in form.questions %}
                <div class="qcmQuestion bs-callout bs-callout-violet">
                    <h4>Question</h4>
                    <div class="row">
                        <div class="col-md-8">{{ form_row(question.libelle, {'<label': 'Libellé'}) }}</div>
                        <div class="col-md-4">{{ form_row(question.typeQuestion, {'label': 'Type de question'}) }}</div>
                    </div>
                    <div class="row hide">
                        <div class="col-md-6">{{ form_row(question.aide, {'label': 'Aide'}) }}</div>
                        <div class="col-md-6">{{ form_row(question.complementReponse, {'label': 'Complément de réponse'}) }}</div>
                    </div>
                    <div>
                        <a class="btn btn-default btn-xs questionOptions"><span class="glyphicon glyphicon-chevron-down"></span> Options</a>
                    </div>
                    <br>
                    <div class="form-group">
                        <div id="common_librarybundle_questiontype_reponses" data-prototype="{{ form_row(question.reponses.vars.prototype)|e }}">
                            <h4>Réponses</h4>
                            <div class="row">
                                <div class="col-md-1 labelReponse">Correcte</div>
                                <div class="col-md-9 labelReponse">Libellé</div>
                            </div>
                            {% for reponse in question.reponses %}
                                <div class="questionReponse bs-callout bs-callout-violet">
                                    <div class='row'>
                                        <div class="col-md-1">{{ form_row(reponse.estCorrecte) }}</div>
                                        <div class="col-md-10">{{ form_row(reponse.libelle) }}</div>
                                    </div>
                                </div>
                            {% endfor %}
                        </div>
                    </div>
                </div>
            {% endfor %}
        </div>
        {{ form_row(form._token) }}
        <br>
        <div class="text-center">
            <button type="submit" class="btn btn-success text-center">Valider</button>
            <a href="{{ path('common_library_theme_index_1', {"idTheme" : idTheme}) }}" class="btn btn-danger text-center">Retour</a>
        </div>
    </form>
{% endblock %}